package cn.icatw.admin.schedule;

import cn.icatw.admin.common.exception.CustomException;
import cn.icatw.admin.domain.Image;
import cn.icatw.admin.domain.ImageJson;
import cn.icatw.admin.service.ImageService;
import cn.icatw.admin.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author icatw
 * @date 2022/10/16
 * @email 762188827@qq.com
 * @apiNote
 */
@Component
@Slf4j
public class AddImageTask {
    @Resource
    private ImageService imageService;

    //每30秒添加一次图片到数据库
    //@Scheduled(cron = "0/20 * *  * * ? ")   //每5秒执行一次
    //public void execute() {
    //    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式
    //    System.out.println("欢迎访问 pan_junbiao的博客 " + df.format(new Date()));
    //}
    //每两分钟添加一次图片到数据库
    //@Scheduled(cron = "0 0/2 * * * ? ")   //两分钟
    @Scheduled(cron = "0 0/30 * * * ? ")   //30分钟
    public void addImageTask() {
        ImageJson imageJson;
        try {
            imageJson = HttpClientUtils.temp();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(500, "调用图片接口失败");
        }
        if (imageJson != null) {
            Image image = new Image();
            image.setTypeId(3L);
            image.setDownloads(0L);
            image.setImageUrl(imageJson.getImgurl());
            image.setImageSize(imageJson.getWidth()+"*"+imageJson.getHeight());
            image.setImageName("动漫");
            boolean flag = imageService.save(image);
            if (flag){
                log.info("------------定时添加图片成功！-------");
                log.info("图片url为："+image.getImageUrl());
            }else {
                log.error("定时添加图片失败！！");
            }
        }
    }
}
